<template>
  <view class="container">
    <!-- 顶部固定区域 -->
    <view class="fixed-header">
      <!-- 顶部导航栏 -->
      <view class="nav-bar">
        <scroll-view 
          class="nav-tabs-scroll"
          scroll-x 
          scroll-with-animation
          :scroll-left="scrollLeft"
          :show-scrollbar="false"
          @click="handleScrollViewClick"
        >
          <view class="nav-tabs">
            <view 
              v-for="(item, index) in tabList" 
              :key="index"
              class="nav-item-wrapper"
              @touchstart="handleTouchStart(index)"
              @touchend="handleTouchEnd"
              @click="handleTabClick(index)"
            >
              <view 
                class="nav-item" 
                :class="{ 
                  active: currentTab === index,
                  shaking: isShaking && activeShakeIndex === index
                }"
              >
                {{ item }}
                <text 
                  class="delete-icon" 
                  v-if="isShaking && activeShakeIndex === index"
                  @click.stop="deleteTab(index)"
                >×</text>
              </view>
            </view>
          </view>
        </scroll-view>
        
        <view class="nav-icons">
          <text class="icon" @click="goCareerExpectancy">+</text>
          <text class="icon" @click="goSearch">🔍</text>
        </view>
      </view>

      <!-- 城市和筛选栏 -->
      <view class="filter-bar">
        <text class="icon" :class="{ 'has-filter': hasFilterConditions }" @click="goJobFiltering">≡</text>
        <text class="city">
          <template v-if="regionName || parentName">
            {{ regionName }} - {{ parentName }}
          </template>
          <template v-else>
            地区无限制
          </template>
        </text>
        <text class="icon" @click="goSelectCity">⇄</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view 
      class="content-area" 
      scroll-y 
      :style="{ height: contentHeight + 'px' }"
      @scrolltolower="loadMore"
    >
      <!-- 加载状态显示 -->
      <view v-if="jobList.length === 0 && !loading" class="empty-state">
        <text>暂无招聘信息</text>
      </view>
      
      <!-- 职位列表 -->
      <view 
        class="job-item" 
        v-for="(job, index) in jobList" 
        :key="index" 
        @click="goRecruitmentDetails(job)"
        v-else
      >
        <view class="job-header">
          <view class="job-title">{{ job.jobName }}</view>
          <view class="salary">{{ setSalary(job.startSalary,job.maxSalary,job.payMethod) }}</view>
        </view>
        <view class="company">{{ job.companyName }}</view>
        <view class="requirements">
          <text>
            {{ truncateText(job.skillRequest) }}
          </text>
        </view>
        <view class="contact">
          <text>◯ {{ job.hrName }}</text>
          <text>{{ job.identity==0?"hr主管":"hr" }}</text>
          <text>{{ job.parentName }} - {{ job.childName }}</text>
        </view>
      </view>
      
      <!-- 底部状态提示 -->
      <view class="load-more" v-if="loading && jobList.length > 0">加载中...</view>
      <view class="no-more" v-if="!loading && jobList.length > 0 && hasNoMore">没有了</view>
    </scroll-view>
    <u-tabbar v-model="current" :list="list" :mid-button="false" @change="tabChangeHandler"></u-tabbar>
  </view>
</template>

<script>
import http from '../../utils/request';
import state from '../../store/state';
import {getCareerExpectByUserId,getRegion,recommendedRecruit,deleteCareerExpect} from '@/api/user.js'
export default {
  data() {
    return {
      list: [
        {
          iconPath: "home",
          selectedIconPath: "home-fill",
          text: "首页",
          count: 2,
          isDot: true,
          customIcon: false,
          pagePath: "/pages/zcy/main"
        },
        {
          iconPath: "chat",
          selectedIconPath: "chat-fill",
          text: "聊天",
          customIcon: false,
          pagePath: "/pages/zj/ChatList"
        },
        {
          iconPath: "account",
          selectedIconPath: "account-fill",
          text: "个人中心",
          count: 23,
          isDot: false,
          customIcon: false,
          pagePath: "/pages/zj/PersonalCenter"
        },
      ],
      current: 0,
      currentTab: 0,
      regionName: "",
      parentName: "",
      loading: false,
      contentHeight: 0,
      jobList: [],
      tabList: ["推荐"],
      careerExpectList: [],
      scrollLeft: 0,
      pageNum: 1,
      pageSize: 5,
      totalCount: 0, // 新增：总数据条数
      hasNoMore: false, // 新增：是否已加载全部
      RecruitInfoVO: {
        industryId: [],
        jobId: [],
        startSalary: null,
        maxSalary: null,
        payMethod: [],
        companyType: [],
        companySize: [],
        regionId: null,
      },
      isShaking: false,
      activeShakeIndex: null,
      longPressTimer: null,
      pressDuration: 1000,
    };
  },
  computed: {
    hasFilterConditions() {
      const vo = this.RecruitInfoVO;
      const i = uni.getStorageSync("expectId");
      if (i == 0) {
        return vo.industryId.length > 0 ||
          vo.jobId.length > 0 ||
          (vo.startSalary !== null && vo.startSalary !== '') ||
          (vo.maxSalary !== null && vo.maxSalary !== '') ||
          vo.payMethod.length > 0 ||
          vo.companyType.length > 0 ||
          vo.companySize.length > 0 ;
      } else {
        return vo.companyType.length > 0 ||
          vo.companySize.length > 0;
      }
    }
  },
  onReady() {
    this.calcContentHeight();
  },
  onLoad() {
    this.getRecruitInfoVO();
    this.getCareerExpect();
    uni.setStorageSync("expectId", 0);
    this.getRecommendedRecruit();
    this.refreshHandler = () => { // 修正事件监听引用
	this.fetchCareerExpect();
	setTimeout(() => {
	    this.shuaXin(this.currentTab);
	}, 500);
    };
    uni.$on('mainPageRefresh', this.refreshHandler);
  },
  onUnload() {
    uni.$off('mainPageRefresh', this.refreshHandler); // 修正事件移除
  },
  methods: {
    handleTouchStart(index) {
      this.longPressTimer = setTimeout(() => {
        this.isShaking = true;
        this.activeShakeIndex = index;
      }, this.pressDuration);
    },

    handleTouchEnd() {
      clearTimeout(this.longPressTimer);
    },

    handleScrollViewClick(e) {
      if (this.isShaking) {
        this.isShaking = false;
        e.stopPropagation();
        return true;
      }
      return false;
    },

    handleTabClick(index) {
      if (this.isShaking) {
        this.isShaking = false;
        return;
      }
      this.switchTab(index);
    },

    deleteTab(index) {
      if (index === 0) {
        uni.showToast({ title: '推荐标签不可删除', icon: 'none' });
        return;
      }

      uni.showModal({
        title: '删除职业期望',
        content: '确定删除此职业期望吗？',
        success: (res) => {
          if (res.confirm) {
            const expectId = this.careerExpectList[index - 1]?.expectId;
            if (!expectId) {
              uni.showToast({ title: '数据异常', icon: 'none' });
              this.isShaking = false;
              return;
            }

            deleteCareerExpect(expectId).then(res => {
              if (res.code === 200) {
                this.tabList.splice(index, 1);
                this.careerExpectList.splice(index - 1, 1);
                // 同步标签列表与数据列表长度
                if (this.tabList.length - 1 !== this.careerExpectList.length) {
                  this.tabList = ['推荐', ...this.careerExpectList.map(item => item.jobName || '未知职位')];
                }
                if (this.currentTab === index) {
                  this.currentTab = 0;
                  this.shuaXin(0);
                } else if (this.currentTab > index) {
                  this.currentTab--;
                }
                uni.showToast({ title: '删除成功' });
              }
            }).finally(() => {
              this.isShaking = false;
            });
          } else {
            this.isShaking = false;
          }
        }
      });
    },

    getRecruitInfoVO() {
      const storedStr = uni.getStorageSync("RecruitInfoVO");
      if (storedStr) {
        try {
          const storedVO = typeof storedStr === 'string' ? JSON.parse(storedStr) : storedStr;
          this.RecruitInfoVO = storedVO;
        } catch (e) { uni.setStorageSync("RecruitInfoVO", JSON.stringify(this.RecruitInfoVO)); }
      }else{
		  uni.setStorageSync("RecruitInfoVO", JSON.stringify(this.RecruitInfoVO));
	  }
      
    },

    getRecommendedRecruit() {
      this.jobList = [];
      this.pageNum = 1;
      this.loading = true; // 开始加载
      this.hasNoMore = false; // 重置状态
      recommendedRecruit(this.RecruitInfoVO, this.pageNum, this.pageSize)
        .then(res => {
          this.jobList = res.data.list || [];
          this.totalCount = res.data.total || 0; // 保存总条数
          this.checkHasNoMore(); // 检查是否加载完毕
		  if (this.RecruitInfoVO.regionId) {
		    getRegion({ regionId: this.RecruitInfoVO.regionId })
		      .then(res => {
		        this.regionName = res.data.regionName || '';
		        this.parentName = res.data.parentName || '';
		      });
		  } else {
		    this.regionName = '';
		    this.parentName = '';
		  }
        })
        .finally(() => {
          this.loading = false; // 结束加载
        });
    },

    getCareerExpect() {
      if (state.userInfo == null) {
        const maxRetry = 5;
        let retryCount = 0;
        const retry = () => {
          if (retryCount >= maxRetry) {
            console.error("获取用户信息失败，已达最大重试次数");
            return;
          }
          retryCount++;
          setTimeout(() => {
            if (state.userInfo != null) {
              this.fetchCareerExpect();
            } else {
              retry();
            }
          }, 500);
        };
        retry();
      } else {
        this.fetchCareerExpect();
      }
    },

    fetchCareerExpect() {
      getCareerExpectByUserId({ userId: state.userInfo.userId })
        .then(res => {
          if (res.code === 200 && res.data && res.data.length) {
            this.careerExpectList = res.data;
            const jobNames = res.data.map(item => item.jobName || '未知职位');
            this.tabList = ['推荐', ...jobNames];
          }
        });
    },

    switchTab(index) {
      this.isShaking = false;
      this.currentTab = index;
      this.shuaXin(index);
    },

    shuaXin(index) {
      if (index === 0) {
        uni.setStorageSync("expectId", 0);
        this.getRecruitInfoVO(); // 重新获取存储的筛选条件
        this.getRecommendedRecruit();
      } else {
        const expectData = this.careerExpectList[index - 1];
        if (!expectData) {
          uni.showToast({ title: '数据加载失败', icon: 'none' });
          return;
        }
        const storedData = uni.getStorageSync("newRecruitInfoVO");
        this.RecruitInfoVO = {
          industryId: [expectData.industryId],
          jobId: [expectData.jobId],
          startSalary: expectData.startSalary,
          maxSalary: expectData.maxSalary,
          payMethod: [expectData.payMethod],
          companyType: storedData?.companyType || [],
          companySize: storedData?.companySize || [],
          regionId: expectData.regionId,
        };
        uni.setStorageSync("expectId", expectData.expectId);
        this.getRecommendedRecruit(); // 重新加载数据
        if (this.RecruitInfoVO.regionId) {
          getRegion({ regionId: this.RecruitInfoVO.regionId })
            .then(res => {
              this.regionName = res.data.regionName || '';
              this.parentName = res.data.parentName || '';
            });
        } else {
          this.regionName = '';
          this.parentName = '';
        }
      }
    },

    calcContentHeight() {
      const query = uni.createSelectorQuery().in(this);
      query.select('.fixed-header').boundingClientRect(data => {
        const systemInfo = uni.getSystemInfoSync();
        this.contentHeight = systemInfo.windowHeight - data.height;
      }).exec();
    },

    loadMore() {
      // 若正在加载或已无更多数据，则不执行
      if (this.loading || this.hasNoMore) return;

      this.loading = true;
      this.pageNum++;
      recommendedRecruit(this.RecruitInfoVO, this.pageNum, this.pageSize)
        .then(res => {
          const newList = res.data.list || [];
          this.jobList = [...this.jobList, ...newList];
          this.totalCount = res.data.total || 0;
          this.checkHasNoMore(); // 检查是否加载完毕
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 新增：检查是否已加载全部数据
    checkHasNoMore() {
      this.hasNoMore = this.jobList.length >= this.totalCount;
    },

    setSalary(startSalary, maxSalary, payMethod) {
      if (payMethod === 4) {
        return `面议`;
      }
      if (payMethod === 0) {
        if (maxSalary === null) return `${startSalary}/日 起`;
        if (startSalary === null) return `最高 ${maxSalary}/日`;
        return `${startSalary} ~ ${maxSalary}/日`;
      }
      if (payMethod === 1) {
        if (maxSalary === null) return `${startSalary}/周 起`;
        if (startSalary === null) return `最高 ${maxSalary}/周`;
        return `${startSalary} ~ ${maxSalary}/周`;
      }
      if (payMethod === 2) {
        if (maxSalary === null) return `${startSalary}/月 起`;
        if (startSalary === null) return `最高 ${maxSalary}/月`;
        return `${startSalary} ~ ${maxSalary}/月`;
      }
      if (payMethod === 3) {
        if (maxSalary === null) return `${startSalary}/时 起`;
        if (startSalary === null) return `最高 ${maxSalary}/时`;
        return `${startSalary} ~ ${maxSalary}/时`;
      }
      return '薪资面议'; // 默认值
    },

    truncateText(text) {
      if (text && text.length > 20) {
        return text.substring(0, 20) + '...';
      }
      return text || '';
    },

    goCareerExpectancy() {
      uni.navigateTo({ url: "/pages/zcy/careerExpectancy" });
    },

    goSelectCity() {
      uni.navigateTo({ url: "/pages/zcy/selectCity" });
    },

    goJobFiltering() {
      if (this.currentTab == 0) {
        uni.navigateTo({ url: "/pages/zcy/jobFiltering" });
      } else {
        uni.navigateTo({ url: "/pages/zcy/newJobFiltering" });
      }
    },

    goSearch() {
      uni.navigateTo({ url: "/pages/zcy/search" });
    },

    goRecruitmentDetails(val) {
      uni.navigateTo({ url: `/pages/zcy/recruitmentDetails?recruitId=${val.recruitId}&userId=${state.userInfo.userId}` });
    },

    tabChangeHandler(index) {
      const pagePath = this.list[index].pagePath;
      uni.switchTab({
        url: pagePath,
        fail: (err) => {
          console.error("跳转失败：", err);
        }
      });
    },
  }
};
</script>

<style scoped>
@keyframes shake {
  0% { transform: translateX(0); }
  25% { transform: translateX(-3px); }
  75% { transform: translateX(3px); }
  100% { transform: translateX(0); }
}

.nav-item-wrapper {
  position: relative;
  display: inline-block;
  margin-right: 20px;
}

.nav-item {
  position: relative;
  padding: 0 25px 0 10px;
  transition: all 0.3s;
}

.shaking {
  animation: shake 0.3s infinite;
  background-color: #f5f5f5;
  border-radius: 15px;
  padding-right: 25px;
}

.delete-icon {
  z-index: 1001;
  position: absolute;
  right: -15px;
  top: 5px;
  color: red;
  font-size: 16px;
  font-weight: bold;
  background: white;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  text-align: center;
  line-height: 16px;
  box-shadow: 0 0 3px rgba(0,0,0,0.3);
}

.has-filter {
  color: #1890ff;
  font-weight: bold;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
  position: relative;
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  height: 50px;
  border-bottom: 1px solid #f0f0f0;
  z-index: 1000;
}

.nav-tabs-scroll {
  flex: 1;
  height: 100%;
  white-space: nowrap;
  max-width: calc(100% - 80px);
}

.nav-tabs {
  display: inline-flex;
  height: 100%;
}

.nav-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 16px;
  color: #666;
  min-width: 60px;
  padding: 0 10px;
  flex-shrink: 0;
}

.nav-item.active {
  color: #1890ff;
  font-weight: bold;
}

.nav-icons {
  display: flex;
  flex-shrink: 0;
  margin-left: 15px;
}

.icon {
  margin-left: 15px;
  font-size: 18px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  height: 40px;
  border-bottom: 1px solid #f0f0f0;
}

.city {
  font-size: 14px;
  color: #333;
}

.content-area {
  width: 100%;
  margin-top: 90px; /* 微调顶部距离 */
  padding: 10px 15px;
}

/* 新增：空状态样式 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
  color: #999;
  font-size: 28rpx;
}

.job-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.job-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.salary {
  margin-right: 30px;
  font-size: 14px;
  color: #ff6b6b;
  font-weight: bold;
}

.company {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.requirements {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 8px;
}

.requirements text {
  font-size: 12px;
  color: #999;
  margin-right: 8px;
  margin-bottom: 5px;
  padding: 3px 8px;
  background-color: #f5f5f5;
  border-radius: 12px;
  display: inline-block;
  white-space: normal;
  word-break: keep-all;
}

.contact {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.contact text {
  margin-right: 10px;
}

.contact text:first-child {
  color: #1890ff;
}

/* 加载状态样式优化 */
.load-more {
  text-align: center;
  padding: 20rpx;
  font-size: 14px;
  color: #999;
}

/* 新增：没有更多数据样式 */
.no-more {
  text-align: center;
  padding: 20rpx;
  font-size: 14px;
  color: #ccc;
}
</style>